package es.juanc.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;

public class IOUtil {
	
	private void copyFiles( String srcDir, String dstDir ) throws IOException {
		
		File path = new File( srcDir );
		File[] files = path.listFiles();
		
		for( int i = 0 ; i < files.length ; i++ ) {
			
			if( files[i].isFile() ) {				
				
				InputStream in = new FileInputStream( srcDir );
				OutputStream out = new FileOutputStream( dstDir );				
				
				byte[] buf = new byte[1024];
				
				int len;				
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				
				in.close();
				out.close(); 				
			}
		}
	}
	
	
	private void copyFilesNIO( String srcDir, String dstDir ) throws IOException {
		
		File path = new File( srcDir );
		File[] files = path.listFiles();
		
		for( int i = 0 ; i < files.length ; i++ ) {
			
			if( files[i].isFile() ) {
				
				// Crea un canal para el origen
				FileChannel srcChannel = new FileInputStream( files[i] ).getChannel();					 
				
				// Crea un canal para el destino
				FileChannel destChannel = new FileOutputStream( new File( dstDir, files[i].getName() ) ).getChannel();					 
				
				// Copia el contenido del archivo origen al destino
				destChannel.transferFrom(srcChannel, 0, srcChannel.size());					 
				
				// Cierra los canales
				srcChannel.close();
				destChannel.close();				
			}
		}
	}
	
	private void removeDir( String dir ) {
		
		File path = new File( dir );
		File[] files = path.listFiles();
		
		for( int i = 0 ; i < files.length ; i++ ) {
			
			if( files[i].isFile() ) {
				files[i].delete();
				//if !files[i].delete() => IOException
			}
		}		
	}
	
}
